package com.github.wxiaoqi.security.biz.codex.biz;

import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.wxiaoqi.security.biz.codex.entity.MarCoupon;
import com.github.wxiaoqi.security.biz.codex.entity.MarCouponBase;
import com.github.wxiaoqi.security.biz.codex.entity.MarCouponRev;
import com.github.wxiaoqi.security.biz.codex.entity.MarCouponUse;
import com.github.wxiaoqi.security.biz.codex.entity.MarIncident;
import com.github.wxiaoqi.security.biz.codex.entity.MarIntegral;
import com.github.wxiaoqi.security.biz.codex.entity.MarIntegralUse;
import com.github.wxiaoqi.security.biz.codex.entity.MarRandomCoupon;
import com.github.wxiaoqi.security.biz.codex.entity.MarScene;
import com.github.wxiaoqi.security.biz.codex.entity.PersonalCouponRelation;
import com.github.wxiaoqi.security.biz.codex.mapper.MarActivityMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.MarCouponMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.MarCouponRevMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.MarCouponUseMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.MarIncidentMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.MarIntegralMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.MarIntegralUseMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.MarRandomCouponMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.MarSceneMapper;
import com.github.wxiaoqi.security.biz.codex.mapper.PersonalCouponRelationMapper;
import com.github.wxiaoqi.security.biz.feign.CrmFeign;
import com.github.wxiaoqi.security.biz.util.NumberUtils;
import com.github.wxiaoqi.security.biz.util.RedEnvelopUtil;
import com.github.wxiaoqi.security.common.admin.pay.response.BaseResponse;
import com.github.wxiaoqi.security.common.biz.request.BaseCouponIntegralQueryReq;
import com.github.wxiaoqi.security.common.biz.request.BestCouponIntegralQueryReq;
import com.github.wxiaoqi.security.common.biz.request.CoupIntegRevCrmReq;
import com.github.wxiaoqi.security.common.biz.request.CouponInfo;
import com.github.wxiaoqi.security.common.biz.request.CouponInfoQueryReq;
import com.github.wxiaoqi.security.common.biz.request.CouponIntegralRefundReq;
import com.github.wxiaoqi.security.common.biz.request.CouponIntegralUseReq;
import com.github.wxiaoqi.security.common.biz.request.CouponReceiveReq;
import com.github.wxiaoqi.security.common.biz.request.CouponStatusReq;
import com.github.wxiaoqi.security.common.biz.request.IntegralReceiveReq;
import com.github.wxiaoqi.security.common.biz.request.WXCouponRevReq;
import com.github.wxiaoqi.security.common.biz.response.BaseCoupInfo;
import com.github.wxiaoqi.security.common.biz.response.BaseCouponIntegralQueryRsp;
import com.github.wxiaoqi.security.common.biz.response.BaseIntegralInfo;
import com.github.wxiaoqi.security.common.entity.PersonalAccountEntity;
import com.github.wxiaoqi.security.common.enums.CustomerTypeEnums;
import com.github.wxiaoqi.security.common.msg.AccountType;
import com.github.wxiaoqi.security.common.msg.Constant;
import com.github.wxiaoqi.security.common.msg.NewSceneType;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;

/**
 * 规则引擎管理
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CodexEngineBiz {
	private final static Logger logger = LoggerFactory.getLogger(CodexEngineBiz.class);
	@Autowired
	private CommonBiz commonBiz;
	@Autowired
	private MarCouponMapper couponMapper;
	@Autowired
	private MarCouponRevMapper couponRevMapper;
	@Autowired
	private MarCouponUseMapper marCouponUseMapper;
	@Autowired
	private MarIntegralUseMapper marIntegralUseMapper;
	@Autowired
	private PersonalCouponRelationMapper personalCouponRelationMapper;
	@Autowired
	private MarActivityMapper marActivityMapper;
	@Autowired
	private MarSceneMapper marSceneMapper;
	@Autowired 
	private MarIncidentMapper marIncidentMapper;
	@Autowired
	private MarRandomCouponMapper randomCouponMapper;
	@Autowired
	private MarIntegralMapper marIntegralMapper;
	@Autowired
	private CrmFeign crmFeign;

	@Value("${randomredenvelope.limit}")
	private String randomRedEnLimit = "5";//随机红包触发限制
	/**
	 * 事件触发的 红包/积分基础查询
	 * 
	 * @return 红包列表信息和积分列表信息
	 */
	public BaseCouponIntegralQueryRsp baseCouponIntegralQuery(BaseCouponIntegralQueryReq param) {
		logger.info("事件触发的 红包/积分基础查询-请求参数：{}" + EntityUtils.beanToMap(param));
		/**
		 * 红包 ：普通红包和随机红包（领取方式都是手动领取） 1、查询可以领取的红包 如果是普通红包-则需要 检验红包领取次数是否达到上限
		 * 、检验该会员针对该红包的领取上限 如果是随机红包-则直接 检验红包领取次数是否达到上限 2、对于被动领取的红包和随机红包
		 * -调用crm接口自动领取。
		 */
		BaseCouponIntegralQueryRsp rsp = new BaseCouponIntegralQueryRsp();
		// 用户信息和商户信息校验
		
		String platformId = param.getPlatformId();
		String personalId = param.getPersonalId();
		String merchantId = param.getMerchantId();
		
		Map<String, Object> perReqMap = new HashMap<String, Object>();
		perReqMap.put("platformId", platformId);
		perReqMap.put("personalId", personalId);
		Map<String, Object> merReqMap = new HashMap<String, Object>();
		merReqMap.put("platformId", platformId);
		merReqMap.put("merchantId", merchantId);
		String custResult = commonBiz.custBaseQuery(perReqMap);
		if ("false".equals(custResult)) {
			rsp.setCode(ResponseCode.PER_NOTEXIST.getCode());
			rsp.setMsg(ResponseCode.PER_NOTEXIST.getMessage());
			return rsp;
		}
		String merResult = commonBiz.queryMerchantInfo(merReqMap);
		if ("false".equals(merResult)) {
			rsp.setCode(ResponseCode.MER_NOTEXIST.getCode());
			rsp.setMsg(ResponseCode.MER_NOTEXIST.getMessage());
			return rsp;
		}

		List<BaseCoupInfo> basecouponList = new ArrayList<BaseCoupInfo>();
		List<BaseCoupInfo> basecouponListResp = new ArrayList<BaseCoupInfo>();
		List<BaseIntegralInfo> baseintegralList = new ArrayList<BaseIntegralInfo>();
		try {
			List<MarCoupon> couplist = (List<MarCoupon>) commonBiz.getCoupInciRev(Constant.COUPON_CODE,
					param.getIncidentId());// 获取可领取的红包列表
			List<MarIntegral> interglist = (List<MarIntegral>) commonBiz.getCoupInciRev(Constant.INTEGRAL_CODE,
					param.getIncidentId());// 获取可领取积分列表
			List<CouponInfo> marInfoList = new ArrayList<CouponInfo>();// 被动领取的红包
			if (null != couplist && couplist.size() > 0) {// 存在可以领取的红包
				for (MarCoupon coup : couplist) {
					// 检验是否可以领取
					if (!commonBiz.checkCoupInciLimit(coup, Constant.COUPON_CODE)
							&& !commonBiz.checkCoupIncRev(coup, Constant.COUPON_CODE, param.getPersonalId())
							//&& !commonBiz.checkSetAmount(coup, Constant.COUPON_CODE) 此处是随机立减时 对金额的校验
							&& !commonBiz.chechIsReceived(coup, Constant.COUPON_CODE, param.getMerOrderNo())) {
						String effectiveStatus = "00";//是否有效
						String valdateTime="";//有效期
						String coupSerialNumber="";//红包流水号
						BaseCoupInfo baseCoup = new BaseCoupInfo();
						//如果是普通红包-校验红包是否有效
						if(Constant.COMMON_COUPON.equals(coup.getCouType())){//普通红包有红包使用的有效期
							// 红包流水号
							coupSerialNumber = NumberUtils.coupiInegSerialNumber();
							baseCoup.setCouponSerialNo(coupSerialNumber);
							Date useStartDate = coup.getStartTime();
							Date useEndDate = coup.getEndTime();
							// 获取当前日期 进行日期判断
							SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
							Calendar calendar = Calendar.getInstance();
							calendar.setTime(new Date());
							String date = formatter.format(calendar.getTime());
							String useStartDateStr = formatter.format(useStartDate);
							String useEndDateStr = formatter.format(useEndDate);
							//红包有效状态 00：有效 01：无效
							if (date.compareTo(useStartDateStr) < 0 || date.compareTo(useEndDateStr) > 0) {
								effectiveStatus = "01";
							} else {
								effectiveStatus = "00";
							}
							SimpleDateFormat dfformat = new SimpleDateFormat("yyyy-M-d");
							valdateTime = dfformat.format(coup.getStartTime()) + " 至 "
									+ dfformat.format(coup.getEndTime());
							baseCoup.setValdateTime(valdateTime);
							baseCoup.setTotalPay(String.valueOf(coup.getTotalPay()));
							baseCoup.setSubtraction(String.valueOf(coup.getSubtraction()));
							baseCoup.setEffectiveStatus(effectiveStatus);
						}
						baseCoup.setCouponId(coup.getCouId());
						baseCoup.setCouponType(coup.getCouType());
						baseCoup.setPayment(coup.getPayment());
						// 红包使用场景
						String sceneIds = coup.getSceneId();
						String sceneStr = getSceneStr(sceneIds);
						logger.info("事件触发的 红包/积分基础查询-获取的红包应用场景：" + sceneStr);
						baseCoup.setScenes(sceneStr);
						baseCoup.setSceneId(sceneIds);
						//根据配置的随机红包触发的阀值和实际付款金额比较，如果实际付款金额低于阀值则无法触发;
						if(Constant.RANDOM_COUPON.equals(coup.getCouType())&&!StringUtils.isEmpty(param.getMerOrderNo())){
							//是随机红包且订单号不能为空
							Map<String,Object>amount=couponMapper.getAmountByOrderNo(param.getMerOrderNo());
							logger.info("支付金额查询Map...................：" + amount);
							if(null!=amount && null==amount.get("amount")){//支付金额
								amount.put("amount", BigDecimal.ZERO);
							}else if(null==amount){
								amount = new HashMap<String,Object>();
								amount.put("amount", BigDecimal.ZERO);
							}
							logger.info("事件触发的 红包/积分基础查询-获取随机红包支付金额：" +amount.get("amount")+"--配置文件中设置的阀值");
							if(Double.valueOf(String.valueOf(amount.get("amount")) )>=Double.valueOf(randomRedEnLimit)){
								baseCoup.setEffectiveStatus("00");//随机红包有效-触发前端拆字页面
							}else{
								baseCoup.setEffectiveStatus("01");//随机红包无效-触发前端拆字页面
							}
						}
						basecouponListResp.add(baseCoup);
						// 若是被动领取的红包都是调用crm接口完成领取的
						if ("01".equals(coup.getPayment())) {// 自动领取
							CouponInfo info = new CouponInfo();
							info.setCouponId(coup.getCouId());
							info.setCouponSerialNo(coupSerialNumber);
							info.setSceneId(coup.getSceneId());
							info.setEffectiveStatus(effectiveStatus);
							marInfoList.add(info);
							basecouponList.add(baseCoup);
						}
					}
				}
			}
			/**
			 * 积分 检验
			 */
			int intergCount = 0;
			if (null != interglist && interglist.size() > 0) {
				for (MarIntegral interg : interglist) {
					if (!commonBiz.checkCoupInciLimit(interg, Constant.INTEGRAL_CODE) && !commonBiz
							.checkCoupIncRev(interg, Constant.INTEGRAL_CODE, param.getPersonalId())
							&& !commonBiz.chechIsReceived(interg, Constant.INTEGRAL_CODE, param.getMerOrderNo())) {
						BaseIntegralInfo baseinterg = new BaseIntegralInfo();
						baseinterg.setIntegralId(interg.getIntegralId());
						baseinterg.setIntegralAmt(String.valueOf(interg.getIntegralAmt()));
						baseintegralList.add(baseinterg);
						intergCount += interg.getIntegralAmt();
					}
				}
			}
			// 调用crm完成被动领取红包
			if (null != marInfoList && marInfoList.size() > 0) {
				CoupIntegRevCrmReq crmReq = new CoupIntegRevCrmReq();
				crmReq.setPlatformId(param.getPlatformId());
				crmReq.setPersonalId(param.getPersonalId());
				crmReq.setMerchantId(param.getMerchantId());
				crmReq.setBusinessType("10");
				crmReq.setCouponList(marInfoList);
				boolean isok = commonBiz.coupIncRevbyCrm(crmReq, basecouponList, null, param.getPersonalId(),
						param.getIncidentId(), param.getMerOrderNo(), "1");//1表示自动领取
			}
			/*
			 * 调用crm领取服务领取积分（积分是被动领取的）
			 */
			if (intergCount > 0) {
				CoupIntegRevCrmReq crmReq = new CoupIntegRevCrmReq();
				crmReq.setPlatformId(param.getPlatformId());
				crmReq.setPersonalId(param.getPersonalId());
				crmReq.setMerchantId(param.getMerchantId());
				crmReq.setBusinessType("20");
				crmReq.setIntegralAmount(String.valueOf(intergCount));
				boolean isok = commonBiz.coupIncRevbyCrm(crmReq, null, baseintegralList, param.getPersonalId(),
						param.getIncidentId(), param.getMerOrderNo(), null);
			}
		} catch (Exception e) {
			logger.info(" 事件触发的 红包/积分基础查询报错" + e.getMessage());
			rsp.setCode("500");
			rsp.setMsg(e.getMessage());
			rsp.setCouponList(basecouponListResp);
			rsp.setIntegralList(baseintegralList);
			logger.info("事件触发的 红包/积分基础查询-返回参数：{}" + EntityUtils.beanToMap(rsp));
			e.printStackTrace();
			return rsp;
		}
		rsp.setCode(ResponseCode.OK.getCode());
		rsp.setMsg(ResponseCode.OK.getMessage());
		rsp.setCouponList(basecouponListResp);
		rsp.setIntegralList(baseintegralList);
		logger.info("事件触发的 红包/积分基础查询-返回参数：{}" + EntityUtils.beanToMap(rsp));
		return rsp;
	}

	/**
	 * 最优优惠券查询 1、CRM获取用户全部的有效优惠券，以及积分 2、根据优惠券编号，查询出优惠券完整信息
	 * 3、根据支付金额判断最优惠，可用，不可用，优惠券
	 * 
	 * @param amt
	 *            抵扣前付款金额
	 */
	public Map<String, Object> queryBestCoupon(BestCouponIntegralQueryReq accountingBalanceRechargeReq) {
		logger.info("最优优惠券查询-请求参数：{}" + EntityUtils.beanToMap(accountingBalanceRechargeReq));
		// 将积分加入到返回中
		Map<String, Object> result = new HashMap<String, Object>();
		// 用户信息校验
		String platformId = accountingBalanceRechargeReq.getPlatformId();
		String personalId = accountingBalanceRechargeReq.getPersonalId();
		Map<String, Object> custReqMap = new HashMap<String, Object>();
		custReqMap.put("platformId", platformId);
		custReqMap.put("personalId", personalId);
		String custResult = commonBiz.custBaseQuery(custReqMap);
		if ("false".equals(custResult)) {
			result.put("code", ResponseCode.PER_NOTEXIST.getCode());
			result.put("msg", ResponseCode.PER_NOTEXIST.getMessage());
			logger.info("最优优惠券查询-返回参数：{}" + result);
			return result;
		}
		
		
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("platformId", platformId);
		reqMap.put("customerType", CustomerTypeEnums.per_user.getCode());
		reqMap.put("accountType", AccountType.ACC_INTEGRAL.getCode());
		reqMap.put("personalId", personalId);
		Map<String, Object> respMap = crmFeign.accountQuery(reqMap);
		// 积分余额
		String cashAcBal = "0";
		if (null != respMap && ResponseCode.OK.getCode().equals(respMap.get("code"))) {
			PersonalAccountEntity personalAccountEntity = (PersonalAccountEntity) respMap.get("accountInfo");
			if (null != personalAccountEntity) {
				cashAcBal = personalAccountEntity.getAccountBalance().setScale(0).toString();
			}
		}
		logger.info("用户的积分余额为：" + cashAcBal);
		
		// CRM获取用户全部的有效优惠券，以及积分
		String sceneId = accountingBalanceRechargeReq.getSceneId();
		String amts = accountingBalanceRechargeReq.getOrderAmt();
		BigDecimal amt = new BigDecimal(amts);
		String sceneID = '%' + sceneId + '%';
		List<MarCouponBase> useList1 = new ArrayList<MarCouponBase>();
		// 查询可使用的优惠券
		List<MarCouponRev> list = couponRevMapper.selectUseAbleBetween(personalId, sceneID);
		if (list.size() == 0 || list == null) {
			MarScene record = new MarScene();
			record.setSceneCode(sceneId);
			MarScene selectOne = marSceneMapper.selectOne(record);
			if(null != selectOne){
				result.put("marketingSwitch", selectOne.getMarketingSwitch());
			}
			result.put("code", ResponseCode.OK.getCode());
			result.put("msg", ResponseCode.COUPON_IS_NULL.getMessage());
			result.put("couponList", useList1);
			result.put("cashAcBal", cashAcBal);
			logger.info("最优优惠券查询-返回参数：{}" + result);
			return result;
		}
		// 可用普通红包
		List<MarCouponBase> useComonList = new ArrayList<MarCouponBase>();
		// 可用随机红包
		List<MarCouponBase> useRondomList = new ArrayList<MarCouponBase>();
		// 可用的红包总金额
		List<MarCouponBase> useList = new ArrayList<MarCouponBase>();
		// 不可用红包
		List<MarCouponBase> noUseList = new ArrayList<MarCouponBase>();
		// 区分可用不可用
		for (MarCouponRev map : list) {
			// 判断红包是否使用过
			PersonalCouponRelation personalCouponRelation = new PersonalCouponRelation();
			String couSerial = map.getCouSerial();
			personalCouponRelation.setCouponSerialNo(couSerial);
			personalCouponRelation.setPlatformId(platformId);
			personalCouponRelation.setPersonalId(personalId);
			personalCouponRelation.setUseStatus("00");
			List<PersonalCouponRelation> list2 = personalCouponRelationMapper.select(personalCouponRelation);
			logger.info("。。。personalId。。。{}" + personalId);
			logger.info("。。。红包流水号。。。{}" + couSerial);
			logger.info("查询红包使用情况。。。{}" + list2.size());
			if (list2.size() != 1) {
				continue;
			}
			MarCouponBase marCouponBase = new MarCouponBase();
			String cId = map.getCouId();
			String couponSerialNo = map.getCouSerial();
			MarCoupon coupon = couponMapper.selectCoup(cId);
			if (coupon == null) {
				continue;
			}
			String payment = coupon.getPayment();
			String sceneIdStr = coupon.getSceneId();
			String sceneStr = getSceneStr(sceneIdStr);
			logger.info("最优优惠券查询-获取的红包应用场景：" + sceneStr);
			marCouponBase.setSceneIds(sceneIdStr);
			marCouponBase.setScene(sceneStr);
			marCouponBase.setCouponId(cId);
			marCouponBase.setCouponSerialNo(couponSerialNo);
			marCouponBase.setIsOptimal("00");
			marCouponBase.setPayment(payment);
			marCouponBase.setCouponAmt(map.getCouponAmt());
			marCouponBase.setCouType(coupon.getCouType());
			/**
			 * 如果是普通红包
			 * */
			if(Constant.COMMON_COUPON.equals(map.getCouType())){
				String subtraction = coupon.getSubtraction().toString();
				String totalPay = coupon.getTotalPay().toString();
				Date startTime = coupon.getStartTime();
				Date endTime = coupon.getEndTime();
				SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d");
				String startTimeStr = format.format(startTime);
				String endTimeStr = format.format(endTime);
				BigDecimal tatalPay = coupon.getTotalPay();
				if (tatalPay == null) {
					continue;
				}
				marCouponBase.setSubtraction(subtraction);
				marCouponBase.setTotalPay(totalPay);
				// 使用日期
				marCouponBase.setValdateTime(startTimeStr + " 至 " + endTimeStr + "可用");
				if (amt.compareTo(tatalPay) >= 0) {//订单金额大于红包满减金额上限
					// 可用
					marCouponBase.setIsUsable("00");
					useComonList.add(marCouponBase);
				} else {
					// 不可用
					marCouponBase.setIsUsable("01");
					noUseList.add(marCouponBase);
				}
			}
			/**
			 * 如果是随机红包
			 * 随机红包没有满减限制，只要配置对应的应用场景就能使用该红包
			 * */ 
			if(Constant.RANDOM_COUPON.equals(map.getCouType())){
				marCouponBase.setIsUsable("00");
				useRondomList.add(marCouponBase);
			}

		}
		// 根据满减金额判断最优,降序排列第一个即使最优
		/**
		 * 普通红包满减最优排序
		 * */ 
		if(useComonList.size()>0){
			for (int i = 0; i < useComonList.size(); i++) {
				for (int j = 0; j < useComonList.size() - 1; j++) {
					if (Long.valueOf(useComonList.get(j).getSubtraction()) < Long.valueOf(useComonList.get(j + 1).getSubtraction())) {
						MarCouponBase c;
						c = useComonList.get(j);
						useComonList.set(j, useComonList.get(j + 1));
						useComonList.set(j + 1, c);
					}
				}
			}	
		}

		/**
		 * 随机立减的红包最优排序
		 * */
		if(useRondomList.size()>0){
			for (int i = 0; i < useRondomList.size(); i++) {
				for (int j = 0; j < useRondomList.size() - 1; j++) {
					//Long.valueOf(useRondomList.get(j).getSubtraction()) < Long.valueOf(useRondomList.get(j + 1).getSubtraction())
					if (useRondomList.get(j).getCouponAmt().compareTo(useRondomList.get(j + 1).getCouponAmt())<0) {
						MarCouponBase c= useRondomList.get(j);
						useRondomList.set(j, useRondomList.get(j + 1));
						useRondomList.set(j + 1, c);
					}
				}
			}
		}
		/**
		 * 比较 普通红包和随机红包首个（即冒泡排序后第一个是最优的）
		 * */
		if(useComonList.size()>0&&useRondomList.size()>0){
			if(useComonList.get(0).getCouponAmt().compareTo(useRondomList.get(0).getCouponAmt())<0){
				useComonList.add(0, useRondomList.get(0));
				useRondomList.remove(0);
			}
		}
		useList.addAll(useComonList);
		useList.addAll(useRondomList);
		// 最优项设为01
		if (useList.size() > 0) {
			MarCouponBase co = useList.get(0);
			co.setIsOptimal("01");
			useList.set(0, co);
		}
		// 将不可用优惠券加入到可用列表中
		useList.addAll(noUseList);

		//新增营销场景开关字段   add by hexufeng
		MarScene record = new MarScene();
		record.setSceneCode(sceneId);
		MarScene selectOne = marSceneMapper.selectOne(record);
		if(null != selectOne){
			result.put("marketingSwitch", selectOne.getMarketingSwitch());
		}
		result.put("couponList", useList);
		result.put("cashAcBal", cashAcBal);
		result.put("code", ResponseCode.OK.getCode());
		result.put("msg", ResponseCode.OK.getMessage());
		logger.info("最优优惠券查询-返回参数：{}" + result);
		return result;
	}

	/**
	 * 红包积分消费服务 1.判断是积分消费还是红包消费 2.消费表中保存记录
	 * 
	 */
	public BaseResponse consume(CouponIntegralUseReq couponIntegralUseReq) {
		logger.info("红包积分消费服务-传入参数：{}" + EntityUtils.beanToMap(couponIntegralUseReq));
		BaseResponse result = new BaseResponse();
		String platformId = couponIntegralUseReq.getPlatformId();
		String personalId = couponIntegralUseReq.getPersonalId();
		String merchantId = couponIntegralUseReq.getMerchantId();
		String sceneId = couponIntegralUseReq.getSceneId();
		String merOrderNo = couponIntegralUseReq.getMerOrderNo();
		String couponId = couponIntegralUseReq.getCouponId();
		String couponSerialNo = couponIntegralUseReq.getCouponSerialNo();
		String integralAmount = couponIntegralUseReq.getIntegralAmount();
		MarIntegralUse integralUse = new MarIntegralUse();
		MarCouponUse couponUse = new MarCouponUse();
		int integralResult = 0;
		int couponResult = 0;
		if (!StringUtils.isEmpty(couponId)) {
			/*MarCoupon marCouponReq = new MarCoupon();
			marCouponReq.setCouId(couponId);*/
			MarCoupon marCoupon = couponMapper.selectCoup(couponId);
			if(null!=marCoupon){
				couponUse.setActId(marCoupon.getActId());
			}
			if(null!=couponIntegralUseReq.getCouponAmt()){
				couponUse.setCouponAmt(new BigDecimal(couponIntegralUseReq.getCouponAmt()));//新增的抵扣金额
			}
			couponUse.setPersonalId(personalId);
			couponUse.setMerchantId(merchantId);
			couponUse.setPlatformId(platformId);
			couponUse.setSceneId(sceneId);
			couponUse.setMerorderno(merOrderNo);
			couponUse.setCouId(couponId);
			couponUse.setCouSerial(couponSerialNo);
			couponUse.setUseTime(new Date());
			couponUse.setTxstatus("00");
			couponResult = marCouponUseMapper.insertSelective(couponUse);
			if (couponResult > 0) {
				result.setCode(ResponseCode.OK.getCode());
				result.setMsg(ResponseCode.OK.getMessage());
			} else {
				result.setCode(ResponseCode.COUPON_USE_SAVE_FAILED.getCode());
				result.setMsg(ResponseCode.COUPON_USE_SAVE_FAILED.getMessage());
				return result;
			}
		}
		if (!StringUtils.isEmpty(integralAmount)) {
			//新增字段  积分抵扣金额
			if(null!=couponIntegralUseReq.getIntegralAmt()){
				integralUse.setIntegralDeductionAmt(new BigDecimal(couponIntegralUseReq.getIntegralAmt()));
			}
			integralUse.setPersonalId(personalId);
			integralUse.setMerchantId(merchantId);
			integralUse.setPlatformId(platformId);
			integralUse.setSceneId(sceneId);
			BigDecimal dd = new BigDecimal(String.valueOf(integralAmount));
			int intIntegralAmount = dd.intValue();
			integralUse.setIntegralAmt(intIntegralAmount);
			integralUse.setUseTime(new Date());
			integralUse.setTxstatus("00");
			integralUse.setMerorderno(merOrderNo);
			integralResult = marIntegralUseMapper.insert(integralUse);
			if (integralResult > 0) {
				result.setCode(ResponseCode.OK.getCode());
				result.setMsg(ResponseCode.OK.getMessage());
			} else {
				result.setCode(ResponseCode.INTEGRAL_USE_SAVE_FAILED.getCode());
				result.setMsg(ResponseCode.INTEGRAL_USE_SAVE_FAILED.getMessage());
			}
		}
		logger.info("红包积分消费服务-返回参数：{}" + EntityUtils.beanToMap(result));
		return result;
	}

	/***
	 * 红包优惠信息查询
	 * 
	 */
	public Map<String, Object> selectCouponPreferential(CouponInfoQueryReq couponInfoQueryReq) {
		logger.info("红包优惠信息查询服务-传入参数：{}" + EntityUtils.beanToMap(couponInfoQueryReq));
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("couId", couponInfoQueryReq.getCouponId());
		param.put("couponSerialNo", couponInfoQueryReq.getCouponSerialNo());
		MarCoupon record = couponMapper.getCouponPreferential(param);
		if (record == null) {
			result.put("code", ResponseCode.COUPON_IS_NULL.getCode());
			result.put("msg", ResponseCode.COUPON_IS_NULL.getMessage());
		} else {
			if(Constant.COMMON_COUPON.equals(record.getCouType())){
				Date useStartDate = record.getStartTime();
				Date useEndDate = record.getEndTime();
				// 获取当前日期 进行日期判断
				SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				String date = formatter.format(calendar.getTime());
				String useStartDateStr = formatter.format(useStartDate);
				String useEndDateStr = formatter.format(useEndDate);
				if (date.compareTo(useStartDateStr) < 0 || date.compareTo(useEndDateStr) > 0) {
					result.put("code", ResponseCode.COUPON_IS_EXPIRED.getCode());
					result.put("msg", ResponseCode.COUPON_IS_EXPIRED.getMessage());
					logger.info("红包优惠信息查询服务-返回参数：{}" + result);
					return result;
				}
				result.put("totalPay",String.valueOf(record.getTotalPay()));
				result.put("subtraction", String.valueOf(record.getSubtraction()));
			}else{
				result.put("totalPay","");
				result.put("subtraction","");
			}
			result.put("couponAmt", String.valueOf(record.getCouponAmt()));//随机红包抵扣金额
			result.put("code", ResponseCode.OK.getCode());
			result.put("msg", ResponseCode.OK.getMessage());
		}
		logger.info("红包优惠信息查询服务-返回参数：{}" + result);
		return result;
	}

	/**
	 * 查询红包使用状态，已使用待使用,未使用,已过期
	 */
	public Map<String, Object> couponStatus(CouponStatusReq couponStatusReq) {
		logger.info("查询红包使用状态服务-传入参数：{}" + EntityUtils.beanToMap(couponStatusReq));
		Map<String, Object> map = new HashMap<String, Object>();
		String platformId = couponStatusReq.getPlatformId();
		String personalId = couponStatusReq.getPersonalId();
		// 用户信息校验
		Map<String, Object> custReqMap = new HashMap<String, Object>();
		custReqMap.put("platformId", platformId);
		custReqMap.put("personalId", personalId);
		String custResult = commonBiz.custBaseQuery(custReqMap);
		if ("false".equals(custResult)) {
			map.put("code", ResponseCode.MER_NOTEXIST.getCode());
			map.put("msg", ResponseCode.MER_NOTEXIST.getMessage());
			logger.info("查询红包使用状态服务-返回参数：{}" + map);
			return map;
		}

		List<MarCoupon> usedList = couponMapper.queryCouponUsed(personalId, platformId);
		List<MarCoupon> noUsedList = couponMapper.queryCouponNoUsed(personalId, platformId);
		List<MarCoupon> overDateList = couponMapper.queryCouponOverDate(personalId, platformId);
		List<MarCoupon> onUseList = couponMapper.queryCouponOnUse(personalId, platformId);
		/**
		 * 将使用场景转化为汉字
		 */
		List<Map<String, Object>> overDateMapList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> usedMapList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> noUsedMapList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> onUsedMapList = new ArrayList<Map<String, Object>>();
		//说明红包是冻结状态 ---status 00待使用01冻结02已使用03已过期
		SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d");
		if (overDateList != null && overDateList.size() > 0) {
			for (MarCoupon marCoupon : overDateList) {
				String startDate="";
				String endDate="";
				if(null!=marCoupon.getStartTime()&&!"".equals(marCoupon.getStartTime())){
					startDate = format.format(marCoupon.getStartTime());
					endDate = format.format(marCoupon.getEndTime());
				}
				Map<String, Object> marMap = beanToMap(marCoupon);
				String sceneIds = marCoupon.getSceneId();
				String sceneStr = getSceneStr(sceneIds);
				logger.info("红包记录查询-获取待使用的已经过期的红包应用场景：" + sceneStr);
				marMap.put("scene", sceneStr);
				marMap.put("startDate", startDate);
				marMap.put("endDate", endDate);
				marMap.put("status", "03");
				overDateMapList.add(marMap);
			}
		}
		if (onUseList != null && onUseList.size() > 0) {
			for (MarCoupon marCoupon : onUseList) {
				String startDate="";
				String endDate="";
				if(null!=marCoupon.getStartTime()&&!"".equals(marCoupon.getStartTime())){
					startDate = format.format(marCoupon.getStartTime());
					endDate = format.format(marCoupon.getEndTime());
				}
				Map<String, Object> marMap = beanToMap(marCoupon);
				String sceneIds = marCoupon.getSceneId();
				String sceneStr = getSceneStr(sceneIds);
				logger.info("红包记录查询-获取待使用的已经过期的红包应用场景：" + sceneStr);
				marMap.put("scene", sceneStr);
				marMap.put("startDate", startDate);
				marMap.put("endDate", endDate);
				marMap.put("status", "01");
				onUsedMapList.add(marMap);
			}
		}
		if (usedList != null && usedList.size() > 0) {
			for (MarCoupon marCoupon : usedList) {
				String startDate="";
				String endDate="";
				if(null!=marCoupon.getStartTime()&&!"".equals(marCoupon.getStartTime())){
					startDate = format.format(marCoupon.getStartTime());
					endDate = format.format(marCoupon.getEndTime());
				}
				Map<String, Object> marMap = beanToMap(marCoupon);
				String sceneIds = marCoupon.getSceneId();
				String sceneStr = getSceneStr(sceneIds);
				logger.info("红包记录查询-获取的已使用的红包应用场景：" + sceneStr);
				marMap.put("scene", sceneStr);
				marMap.put("startDate", startDate);
				marMap.put("endDate", endDate);
				marMap.put("status", "02");
				usedMapList.add(marMap);
			}
		}
		if (noUsedList != null && noUsedList.size() > 0) {
			for (MarCoupon marCoupon : noUsedList) {
				String startDate="";
				String endDate="";
				if(null!=marCoupon.getStartTime()&&!"".equals(marCoupon.getStartTime())){
					startDate = format.format(marCoupon.getStartTime());
					endDate = format.format(marCoupon.getEndTime());
				}
				Map<String, Object> marMap = beanToMap(marCoupon);
				String sceneIds = marCoupon.getSceneId();
				String sceneStr = getSceneStr(sceneIds);
				logger.info("红包记录查询-获取的红包应用场景：" + sceneStr);				
				marMap.put("scene", sceneStr);
				marMap.put("startDate", startDate);
				marMap.put("endDate", endDate);
				marMap.put("status", "00");
				logger.info("。。。personalId。。。{}" + personalId);
				//marMap.put("couType", marCoupon.getCouType());
				//marMap.put("couponAmt", marCoupon.getCouponAmt());
				noUsedMapList.add(marMap);
			}
		}
		noUsedMapList.addAll(onUsedMapList);
		map.put("usedList", usedMapList);
		map.put("noUsedList", noUsedMapList);
		map.put("overDateList", overDateMapList);
		map.put("code", ResponseCode.OK.getCode());
		map.put("msg", ResponseCode.OK.getMessage());
		logger.info("查询红包使用状态服务-返回参数：{}" + map);
		return map;

	}

	public static Map<String, Object> beanToMap(Object obj) {
		Map<String, Object> params = new HashMap<String, Object>(0);
		try {
			PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
			PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
			for (int i = 0; i < descriptors.length; i++) {
				String name = descriptors[i].getName();
				if (!"class".equals(name)) {
					params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return params;
	}

	/**
	 * 红包积分退款
	 * 
	 * @return
	 */
	public BaseResponse refund(CouponIntegralRefundReq couponIntegralRefundReq) {
		logger.info("红包积分退款服务-请求参数：{}" + EntityUtils.beanToMap(couponIntegralRefundReq));
		BaseResponse result = new BaseResponse();
		// 订单号
		String merOrderNo = couponIntegralRefundReq.getMerOrderNo();
		// 平台编号
		String platformId = couponIntegralRefundReq.getPlatformId();
		int integralResult = 0;
		int couponResult = 0;
		MarIntegralUse integralU = new MarIntegralUse();
		integralU.setMerorderno(merOrderNo);
		integralU.setPlatformId(platformId);
		MarIntegralUse integralUse = marIntegralUseMapper.selectOne(integralU);
		if (integralUse != null) {
			logger.info("存在积分使用订单。。。{}" + integralUse);
			integralUse.setTxstatus("01");
			integralResult = marIntegralUseMapper.updateByPrimaryKey(integralUse);
			if (integralResult > 0) {
				result.setCode(ResponseCode.OK.getCode());
				result.setMsg(ResponseCode.OK.getMessage());
			} else {
				result.setCode(ResponseCode.INTEGRAL_REFUND_SAVE_FAILED.getCode());
				result.setMsg(ResponseCode.INTEGRAL_REFUND_SAVE_FAILED.getMessage());
			}
		}

		MarCouponUse couponU = new MarCouponUse();
		couponU.setMerorderno(merOrderNo);
		couponU.setPlatformId(platformId);
		MarCouponUse couponUse = marCouponUseMapper.selectOne(couponU);
		if (couponUse != null) {
			logger.info("存在红包使用订单。。。{}" + couponUse);
			couponUse.setTxstatus("01");
			couponResult = marCouponUseMapper.updateByPrimaryKey(couponUse);
			if (couponResult > 0) {
				result.setCode(ResponseCode.OK.getCode());
				result.setMsg(ResponseCode.OK.getMessage());
			} else {
				result.setCode(ResponseCode.COUPON_REFUND_SAVE_FAILED.getCode());
				result.setMsg(ResponseCode.COUPON_REFUND_SAVE_FAILED.getMessage());
			}
		}
		logger.info("红包积分退款服务-返回参数：{}" + EntityUtils.beanToMap(result));
		return result;
	}
	
	
	/**
	 * 小程序 积分手动领取  
	 */
	public Map<String, Object> integralReceive(IntegralReceiveReq integralReceiveReq) {
		logger.info("积分手动领取服务-请求参数：{}" + EntityUtils.beanToMap(integralReceiveReq));
		Map<String, Object> result = new HashMap<String, Object>();
		String platformId = integralReceiveReq.getPlatformId();
		String personalId = integralReceiveReq.getPersonalId();
		String merchantId = integralReceiveReq.getMerchantId();
		String integralId = integralReceiveReq.getIntegralId();
		String incidentId = integralReceiveReq.getIncidentId();
		String merOrderNo = integralReceiveReq.getMerOrderNo();//订单号
		String orderAmt =integralReceiveReq.getOrderAmt();//订单金额
		
		/**
		 * 积分 检验
		 */
		List<BaseIntegralInfo> baseintegralList = new ArrayList<BaseIntegralInfo>();
		int intergCount = 0;
		MarIntegral marIntegral = marIntegralMapper.selectByIntegralId(integralId);
		logger.info("查询到积分。。{}"+marIntegral);
		if (!commonBiz.checkCoupInciLimit(marIntegral, Constant.INTEGRAL_CODE) && !commonBiz
						.checkCoupIncRev(marIntegral, Constant.INTEGRAL_CODE, personalId)
						&& !commonBiz.chechIsReceived(marIntegral, Constant.INTEGRAL_CODE, merOrderNo)) {
			BaseIntegralInfo baseinterg = new BaseIntegralInfo();
			baseinterg.setIntegralId(marIntegral.getIntegralId());
			baseinterg.setIntegralAmt(String.valueOf(marIntegral.getIntegralAmt()));
			baseintegralList.add(baseinterg);
			intergCount += marIntegral.getIntegralAmt();
			
			logger.info("查询到积分baseintegralList..{}"+baseintegralList);
			logger.info("查询到积分intergCount..{}"+intergCount);
		}
		
		/*
		 * 调用crm领取服务领取积分（积分是被动领取的）
		 */
		if (intergCount > 0) {
			CoupIntegRevCrmReq crmReq = new CoupIntegRevCrmReq();
			crmReq.setPlatformId(platformId);
			crmReq.setPersonalId(personalId);
			crmReq.setMerchantId(merchantId);
			crmReq.setBusinessType("20");
			crmReq.setIntegralAmount(String.valueOf(intergCount));
			logger.info("领取积分crmReq..{}"+crmReq);
			boolean isok = commonBiz.coupIncRevbyCrm(crmReq, null, baseintegralList, personalId,
					incidentId, merOrderNo, null);
			if (isok) {
				result.put("code", ResponseCode.OK.getCode());
				result.put("msg", ResponseCode.OK.getMessage());
			} else {
				result.put("code", ResponseCode.COUPON_REV_FAILED.getCode());
				result.put("msg", ResponseCode.COUPON_REV_FAILED.getMessage());
			}
		}
		return result;
	}
	/***
	 * 红包手动领取 1.查询红包ID是否存在 2.查询红包是否还可以领取 3.调用crm领取红包 4.本地记录保存
	 * 注意： 手动领取随机红包时  须返回随机红包金额
	 */
	public Map<String, Object> couponReceive(CouponReceiveReq couponReceiveReq) {
		logger.info("红包手动领取服务-请求参数：{}" + EntityUtils.beanToMap(couponReceiveReq));
		Map<String, Object> result = new HashMap<String, Object>();
		List<BaseCoupInfo> basecouponList = new ArrayList<BaseCoupInfo>();
		String platformId = couponReceiveReq.getPlatformId();
		String personalId = couponReceiveReq.getPersonalId();
		String merchantId = couponReceiveReq.getMerchantId();
		String incidentId = couponReceiveReq.getIncidentId();
		String couponId = couponReceiveReq.getCouponId();
		String merOrderNo = couponReceiveReq.getMerOrderNo();//订单号
		String orderAmt =couponReceiveReq.getOrderAmt();//订单金额
		/**
		 * 1校验订单号是否必传
		 * 2如果订单号不为空 则直接校验订单的有效性
		 * 根据配置的事件id校验订单号是否是必传项
		 * 根据订单号从crm表中查询订单是否有效
		 * */
		if(null!=incidentId&&!"".equals(incidentId)){
			MarIncident incidentinfo=marIncidentMapper.getMarIncidentByincCode(incidentId);
			if(null !=incidentinfo&&"1".equals(incidentinfo.getIsNeed())){//订单号是必传项
				if(null==merOrderNo||"".equals(merOrderNo)){
					result.put("code", ResponseCode.COUPON_MerOrderNo_IS_NULL.getCode());
					result.put("msg", ResponseCode.COUPON_MerOrderNo_IS_NULL.getMessage());
					logger.info("红包手动领取服务-返回参数：{}" + result);
					return result;
				}
			}
		}
		//订单号不为空的话 则去校验订单号有效性
		if(!StringUtils.isEmpty(merOrderNo)){
			List<String> isexist=couponMapper.checkMerCustNo(merOrderNo);
			if(null==isexist||isexist.size()<=0){
				result.put("code", ResponseCode.COUPON_MerOrderNo_IS_OK.getCode());
				result.put("msg", ResponseCode.COUPON_MerOrderNo_IS_OK.getMessage());
				logger.info("红包手动领取服务-返回参数：{}" + result);
				return result;
			}
		}
		// 用户信息校验和商户信息校验
		Map<String, Object> custReqMap = new HashMap<String, Object>();
		custReqMap.put("platformId", platformId);
		custReqMap.put("personalId", personalId);
		Map<String, Object> merReqMap = new HashMap<String, Object>();
		merReqMap.put("platformId", platformId);
		merReqMap.put("merchantId", merchantId);

		String custResult = commonBiz.custBaseQuery(custReqMap);
		if ("false".equals(custResult)) {
			result.put("code", ResponseCode.PER_NOTEXIST.getCode());
			result.put("msg", ResponseCode.PER_NOTEXIST.getMessage());
			logger.info("红包手动领取服务-返回参数：{}" + result);
			return result;
		}
		String merResult = commonBiz.queryMerchantInfo(merReqMap);
		if ("false".equals(merResult)) {
			result.put("code", ResponseCode.MER_NOTEXIST.getCode());
			result.put("msg", ResponseCode.MER_NOTEXIST.getMessage());
			logger.info("红包手动领取服务-返回参数：{}" + result);
			return result;
		}

		/*MarCoupon marCouponReq = new MarCoupon();
		marCouponReq.setCouId(couponId);*/
		MarCoupon marCoupon = couponMapper.selectCoup(couponId);
		if (marCoupon == null) {
			result.put("code", ResponseCode.COUPON_IS_NULL.getCode());
			result.put("msg", ResponseCode.COUPON_IS_NULL.getMessage());
			logger.info("红包手动领取服务-返回参数：{}" + result);
			return result;
		}

		String coupStatus = marCoupon.getCouStatus();
		if ("01".equals(coupStatus)) {
			result.put("code", ResponseCode.COUPON_REV_FAILED.getCode());
			result.put("msg", ResponseCode.COUPON_REV_FAILED.getMessage());
			logger.info("红包手动领取服务-返回参数：{}" + result);
			return result;
		}

		Date revStartDate = marCoupon.getRevStart();
		Date revEndDate = marCoupon.getRevEnd();
		String effectiveStatus = "00";
		if(Constant.COMMON_COUPON.equals(marCoupon.getCouType())){//如果是普通红包
			Date useStartDate = marCoupon.getStartTime();//红包有效开始时间
			Date useEndDate = marCoupon.getEndTime();//红包有效结束时间
			// 获取当前日期 进行日期判断
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			String date = formatter.format(calendar.getTime());
			String revStartDateStr = formatter.format(revStartDate);
			String revEndDateStr = formatter.format(revEndDate);
			if (date.compareTo(revStartDateStr) < 0 || date.compareTo(revEndDateStr) > 0) {
				result.put("code", ResponseCode.COUPON_IS_EXPIRED.getCode());
				result.put("msg", ResponseCode.COUPON_IS_EXPIRED.getMessage());
				logger.info("红包手动领取服务-返回参数：{}" + result);
				return result;
			}
			String useStartDateStr = formatter.format(useStartDate);
			String useEndDateStr = formatter.format(useEndDate);
			if (date.compareTo(useStartDateStr) < 0 || date.compareTo(useEndDateStr) > 0) {
				effectiveStatus = "01";
			} else {
				effectiveStatus = "00";
			}
		}

		// 检验是否可以领取
		if (!commonBiz.checkCoupInciLimit(marCoupon, Constant.COUPON_CODE)
				&& !commonBiz.checkCoupIncRev(marCoupon, Constant.COUPON_CODE, personalId)
				//&& !commonBiz.checkSetAmount(marCoupon, Constant.COUPON_CODE)随机立减 对设置总金额的校验
				&& !commonBiz.chechIsReceived(marCoupon, Constant.COUPON_CODE, merOrderNo)) {
			List<CouponInfo> infoList = new ArrayList<CouponInfo>();// 调用crm需要的参数
			BaseCoupInfo baseCoup = new BaseCoupInfo();

			baseCoup.setCouponId(couponId);
			baseCoup.setPayment("02");
			baseCoup.setActId(marCoupon.getActId());
			baseCoup.setSceneId((marCoupon.getSceneId()));
			String coupSerialNumber = NumberUtils.coupiInegSerialNumber();
			if(Constant.COMMON_COUPON.equals(marCoupon.getCouType())){//普通红包
				baseCoup.setTotalPay(marCoupon.getTotalPay().toString());
				baseCoup.setSubtraction(marCoupon.getSubtraction().toString());
				baseCoup.setCouponAmt(marCoupon.getSubtraction());
				//红包流水号
				baseCoup.setCouponSerialNo(coupSerialNumber);//流水号
				//红包有效期
				String valdateTime = marCoupon.getStartTime() + "$" + marCoupon.getEndTime();
				baseCoup.setValdateTime(valdateTime);
				baseCoup.setCouponType("00");
				basecouponList.add(baseCoup);
			}
			/***
			 * 根据订单金额和配置金额去比较 只有满足条件是才能获取随机随机红包
			 * 如果订单金额大于配置的金额才能领取红包
			 * 红包领取规则：一档 和两档的红包 是单次的  三档的红包可以无限领取。
			 * --根据订单号校验是否领取过该红包
			 * 验证此红包是否存在可以领取的 有效的红包
			 * 查询用户该红包的领取记录：如果是用户时用户首次领取随机红包的话 则可以有概率获取一档和两档的红包 ，若用户领取过一档或者二档的红包 则只能随机三档的红包
			 * 调用crm领取成功后存入领取记录表 并将随机红包的金额返回前端
			 * */
			//randomRedEnLimit
			//String randomCouponAmt="";//随机红包金额
			String couAmt = "";
			if(Constant.RANDOM_COUPON.equals(marCoupon.getCouType())){//随机红包
				if(!StringUtils.isEmpty(randomRedEnLimit)){//根据红包金额限制生产随机红包
					logger.info("订单金额,订单号。。。。。。。{}",orderAmt,merOrderNo);
					logger.info("金额阈值。。。。。。。{}",randomRedEnLimit);
					if(!StringUtils.isEmpty(orderAmt)&&!StringUtils.isEmpty(merOrderNo)){//订单金额和订单号不能为空才能触发随机红包
						if(Double.valueOf(orderAmt)>=Double.valueOf(randomRedEnLimit)){//订单金额大于配置的金额才会触发随机红包
							MarRandomCoupon coupon =getRadomRedEn(couponId, personalId);
							logger.info("随机红包生成结果。。。。。。。{}",EntityUtils.beanToMap(coupon));
							if(null!=coupon){//
								//baseCoup.setCouponAmt(coupon.getCouAmt());//红包抵扣金额
								baseCoup.setCouponSerialNo(coupon.getCouSerial());//红包流水号
								logger.info("随机红包流水号1。。。。。。。{}",coupon.getCouSerial());
								couAmt = String.valueOf(coupon.getCouAmt());
								baseCoup.setCouponAmt(coupon.getCouAmt());//红包抵扣金额；随机红包不是满减，红包抵扣金额就是红包金额
								baseCoup.setCouLevel(coupon.getCouLevel());
								baseCoup.setCouponType("1");
								basecouponList.add(baseCoup);
								coupSerialNumber = coupon.getCouSerial();
								logger.info("随机红包流水号2。。。。。。。{}",coupSerialNumber);
							}else{
								result.put("code", ResponseCode.COUPON_NOT_REV.getCode());
								result.put("msg", ResponseCode.COUPON_NOT_REV.getMessage());
								logger.info("红包领取失败。。。。。。1");
								return result;
							}
						}else{
							result.put("code", ResponseCode.COUPON_NOT_REV.getCode());
							result.put("msg", ResponseCode.COUPON_NOT_REV.getMessage());
							logger.info("红包领取失败。。。。。。2");
							return result;
						}
					}else{//不符合领取条件则直接返回红包已经领取完
						result.put("code", ResponseCode.COUPON_NOT_REV.getCode());
						result.put("msg", ResponseCode.COUPON_NOT_REV.getMessage());
						logger.info("红包领取失败。。。。。。3");
						return result;
					}
				}else{//如果没有配置的话则直接提示已经领完
					result.put("code", ResponseCode.COUPON_NOT_REV.getCode());
					result.put("msg", ResponseCode.COUPON_NOT_REV.getMessage());
					logger.info("红包领取失败。。。。。。4");
					return result;
				}

			}
			//调用crm参数
			CoupIntegRevCrmReq crmReq = new CoupIntegRevCrmReq();
			crmReq.setPlatformId(platformId);
			crmReq.setPersonalId(personalId);
			crmReq.setMerchantId(merchantId);
			crmReq.setBusinessType("10");
			CouponInfo info = new CouponInfo();
			info.setCouponId(couponId);
			logger.info("红包流水号.................",coupSerialNumber);
			info.setCouponSerialNo(coupSerialNumber);
			info.setSceneId(marCoupon.getSceneId());
			info.setEffectiveStatus(effectiveStatus);
			infoList.add(info);
			crmReq.setCouponList(infoList);
			String revType = "0";//手动领取
			if(!StringUtils.isEmpty(couponReceiveReq.getRevType())){
				revType = couponReceiveReq.getRevType();
			}
			boolean isok = commonBiz.coupIncRevbyCrm(crmReq, basecouponList, null, personalId, incidentId, merOrderNo, revType);
			/**
			 * 领取成功后,存入红包领取记录
			 */
			if (isok) {
				if(Constant.RANDOM_COUPON.equals(marCoupon.getCouType())){
					result.put("couponAmt", couAmt);//随机红包金额
				}
				result.put("code", ResponseCode.OK.getCode());
				result.put("msg", ResponseCode.OK.getMessage());
			} else {
				result.put("code", ResponseCode.COUPON_REV_FAILED.getCode());
				result.put("msg", ResponseCode.COUPON_REV_FAILED.getMessage());
			}
		} else {
			result.put("code", ResponseCode.COUPON_NOT_REV.getCode());
			result.put("msg", ResponseCode.COUPON_NOT_REV.getMessage());
		}
		logger.info("红包手动领取服务-返回参数：{}" + result);
		return result;
	}

	/**
	 * 生产随机红包
	 * **/
	/*
	 *  验证此红包是否存在可以领取的 有效的红包
	 *  查询用户该红包的领取记录：如果是用户时用户首次领取随机红包的话 则可以有概率获取一档和两档的红包 ，若用户领取过一档或者二档的红包 则只能随机三档的红包
	 *  调用crm领取成功后存入领取记录表 并将随机红包的金额返回前端
	 * */
	public MarRandomCoupon getRadomRedEn(String couponId,String merCustNo){
		MarRandomCoupon randomReden=null;
		int is_exist=randomCouponMapper.checkRandomCoupon(couponId);
		if(is_exist>0){//存在可领取的且未领取的红包
			List<MarCouponRev>couponRevs=couponRevMapper.getCouponRev(merCustNo, couponId);
			if(null!=couponRevs&&couponRevs.size()>0){//用户已经领取过
				//根据用户领取的红包
				try {
					boolean flag=false;
					for(MarCouponRev rev:couponRevs){
						if("01".equals(rev.getCouponLevel())||"02".equals(rev.getCouponLevel())){
							logger.info("会员号："+merCustNo+"已领取过一档二档红包");
							flag=true;
						}
						if(flag){//只能从第三档红包中领取
							logger.info("会员号："+merCustNo+"领取第三档的红包");
							//获取三档红包 然后随机抽取一个
							List<MarRandomCoupon>randomCoups=randomCouponMapper.getRandomBylevel(couponId, "03");
							if(null!=randomCoups&&randomCoups.size()>0){
								logger.info("第三档的红包随机总数："+randomCoups.size());
								int randomnum=RedEnvelopUtil.getRandomnext(randomCoups.size());
								logger.info("第三档的红包随机红包数字："+randomnum);
								randomReden=randomCoups.get(randomnum);
								return randomReden;
							}
						}
					}
				} catch (Exception e) {
					logger.info("生产随机红包-返回出错：{}" + e);
					e.printStackTrace();
					return null;
				}

			}
			//第一次领取红包的话则直接从红包池中抽奖
			/**
			 * 获取所有的随机红包
			 * */
			List<MarRandomCoupon>randomCoups=randomCouponMapper.getRandomBylevel(couponId, null);
			logger.info("红包id："+couponId+"--第一次领取随机红包");
			if(null!=randomCoups&&randomCoups.size()>0){
				logger.info("红包随机总数---："+randomCoups.size());
				int randomnum=RedEnvelopUtil.getRandomnext(randomCoups.size());
				logger.info("红包随机数字---："+randomnum);
				randomReden=randomCoups.get(randomnum);
				return randomReden;
			}
		}
		return randomReden;
	}

	/***
	 * 转换红包应用场景 对于的app中文场景
	 */
	public String getSceneStr(String sceneIdStr) {
		StringBuffer sceneStrbuf = new StringBuffer("");
		String sceneStr="";
		String[] sceneIds = sceneIdStr.split(",");
		if (null != sceneIds && sceneIds.length > 0) {
			for (String scence : sceneIds) {
				if (!sceneStrbuf.toString().contains(NewSceneType.getSceneTypename(scence))) {
					sceneStrbuf.append(NewSceneType.getSceneTypename(scence)).append(",");// 场景中文
				}
			}
			sceneStr = sceneStrbuf.toString().substring(0, sceneStrbuf.toString().lastIndexOf(","));
		}
		return sceneStr;
	}



	/***
	 * 小程序-获取可领取红包列表
	 * 
	 * param:事件Id，商户会员号
	 * 
	 */
	public Map<String, Object> getCouponBySceneId(WXCouponRevReq wxCouponRevReq) {
		logger.info("小程序-获取可领取红包列表-请求参数：{}" + EntityUtils.beanToMap(wxCouponRevReq));
		// 返回值
		Map<String, Object> rsp = new HashMap<String, Object>();
		List<Map<String, Object>> couponList = new ArrayList<Map<String, Object>>();
		int total = 0;
		String incidentId = wxCouponRevReq.getIncidentId();
		String merCustNo = wxCouponRevReq.getPersonalId();
		List<MarCoupon> couList = new ArrayList<MarCoupon>();
		if ("".equals(incidentId)) {
			// 通过搜索小程序进入或者朋友推荐进入，查询当前活动所有的可领红包(小程序进入)，小程序事件为010开头后缀为两位数
			String incidentID = "010";
			couList = couponMapper.getCouponsByincCode(incidentID);
			logger.info("小程序-获取可领取红包列表-通过搜索进入：{}" + couList.size());
		} else {
			// 通过海报扫码进入，查询海报二维码场景的红包
			couList = couponMapper.getCouponsByincCode(incidentId);
			logger.info("小程序-获取可领取红包列表-通过扫码进入：{}" + couList.size());
		}

		if (couList.size() == 0 || couList == null) {
			// 该活动无红包可领
			rsp.put("couponList", couponList);
			rsp.put("total", String.valueOf(total));
			logger.info("小程序-获取可领取红包列表-响应参数：{}" + rsp);
			return rsp;
		} else {
			// 添加可领取红包到红包列表
			for (MarCoupon marCoupon2 : couList) {
				// 剔除已领完的红包
				if (!commonBiz.checkCoupInciLimit(marCoupon2, Constant.COUPON_CODE)) {
					String couId = marCoupon2.getCouId();
					logger.info("小程序-获取可领取红包列表-可领取红包ID：{}" + couId);
					// 查出用户之前领取过的红包
					if (!"".equals(merCustNo)) {
						// 查看用户是否领取该红包
						MarCouponRev marCouponRev = new MarCouponRev();
						marCouponRev.setMerCustNo(merCustNo);
						marCouponRev.setCouId(couId);
						List<MarCouponRev> list = couponRevMapper.select(marCouponRev);
						if (list.size() != 0) {
							continue;
						}
					}
					Map<String, Object> marMap = beanToMap(marCoupon2);
					SimpleDateFormat dfformat = new SimpleDateFormat("yyyy-MM-dd");
					String valdateTime = dfformat.format(marCoupon2.getStartTime()) + " 至 "
							+ dfformat.format(marCoupon2.getEndTime()) + "可用";
					String sceneStr = getSceneStr(marCoupon2.getSceneId());
					logger.info("小程序-获取可领取红包列表-可领取的红包应用场景：" + sceneStr);
					sceneStr = "限" + sceneStr;
					marMap.put("scene", sceneStr);
					marMap.put("valdateTime", valdateTime);
					couponList.add(marMap);
					total += 1;
				}
			}
		}
		rsp.put("couponList", couponList);
		rsp.put("total", String.valueOf(total));
		logger.info("小程序-获取可领取红包列表-响应参数：{}" + rsp);
		return rsp;
	}

}
